package com.easyadmin.pro.common.initutils;

import com.alibaba.fastjson.JSONObject;
import com.easyadmin.pro.common.constants.RedisConstants;
import com.easyadmin.pro.common.constants.StatusConstants;
import com.easyadmin.pro.modules.sys.entity.DataDictionaryEntity;
import com.easyadmin.pro.modules.sys.service.IDataDictionaryService;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * packageName com.easyadmin.pro.common.initutils
 *
 * @author 骑着蚂蚁去上天
 * @version JDK 17
 * @className InitDataDictionaryInfo
 * @date 2024/8/26
 * @description 初始化数据集
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class InitDataDictionaryInfo {

    private final IDataDictionaryService dataDictionaryService;

    private final RedisTemplate redisTemplate;


    @PostConstruct
    public void init() {
        List<DataDictionaryEntity> dataInfos = dataDictionaryService.list(new QueryWrapper()
                .eq(DataDictionaryEntity::getStatus, Integer.parseInt(StatusConstants.STATUS_1)));

        if (!CollectionUtils.isEmpty(dataInfos)) {
            Map<String, List<DataDictionaryEntity>> dataInfoMap = dataInfos.stream()
                    .collect(Collectors.groupingBy(DataDictionaryEntity::getDataCode));
            redisTemplate.opsForValue().set(RedisConstants.DATA_DICTIONARY_KEY, JSONObject.toJSONString(dataInfoMap));
        }
    }
}